<?php
namespace zake\foundation\able\traits;


use zake\foundation\stream\WriteStream;

trait WriteTrait
{
    /**
     * @var int
     */
    protected $writeTime = 0;


    /**
     * 写
     * @return resource
     *
     * @author liu.bin 2020-03-31 16:33
     */
    public function getWriteResource()
    {
        return $this->getResource();
    }

    /**
     *
     * @return int
     *
     * @author liu.bin 2020-04-16 09:26
     */
    public function getWriteFd()
    {
        return $this->getFd();
    }


    /**
     * 同步写入
     * @param $sendData
     * @param int $mode
     *
     * @return int
     *
     * @author liu.bin 2020-05-19 14:24
     */
    public function write($sendData,$mode = WriteStream::MODE_PERSIST)
    {
        if(emptyString($sendData)){
            return 0;
        }
        $resource = $this->getWriteResource();
        if(empty($resource)){
            return 0;
        }
        // 发送数据
        $sendSize = stream_socket_sendto($resource,$sendData);
        if($sendSize >= strlen($sendData)){
            return $sendSize;
        }
        if(WriteStream::MODE_PERSIST & $mode){
            // persist
            return $sendSize + $this->write(substr($sendData,$sendSize),$mode);
        }
        return $sendSize;
    }


    public function closeWriteResource()
    {
        if(!$this->isCloseWriteResource()){
            return $this->closeResource();
        }
        return true;
    }


    public function isCloseWriteResource()
    {
        return $this->isCloseResource();
    }


    /**
     * 写入时间
     *
     * @param int|null $time
     * @author liu.bin 2020-03-31 16:43
     */
    public function setWriteTime($time = null)
    {
        $this->writeTime = $time;
    }

    /**
     * 获取上一次写入数据的时间
     *
     * @return int
     * @author liu.bin 2020-03-28 21:18
     */
    public function getWriteTime()
    {
        return $this->writeTime;
    }

}